package com.jewelry.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jewelry.dto.CategoryDTO;
import com.jewelry.entity.Category;
import com.jewelry.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping()
    public Map<String, Object> getAllCategory1() {
        HashMap<String, Object> map = new HashMap<>();
        List<CategoryDTO> categories = categoryService.getCategories();
        map.put("code", 200);
        map.put("message", "success");
        map.put("data", categories);
        return map;
    }

    @GetMapping("/child")
    public Map<String, Object> getChildCategory() {
        HashMap<String, Object> map = new HashMap<>();
        List<Category> categoryList = categoryService.list(new LambdaQueryWrapper<Category>().isNotNull(Category::getParentId));
        map.put("code", 200);
        map.put("message", "success");
        map.put("data", categoryList);
        return map;
    }

    @GetMapping("/{pId}")
    public Map<String, Object> getCategoryByParentId(@PathVariable("pId") Integer pId) {
        HashMap<String, Object> map = new HashMap<>();
        List<Category> categoryList = categoryService.list(new LambdaQueryWrapper<Category>().eq(Category::getParentId, pId));
        map.put("code", 200);
        map.put("message", "success");
        map.put("data", categoryList);
        return map;
    }

    @PostMapping
    public Map<String, Object> addCategory(@RequestBody Category category) {
        HashMap<String, Object> map = new HashMap<>();
        boolean result = categoryService.saveOrUpdate(category);
        if (result) {
            map.put("message", "success");
        } else {
            map.put("message", "fail");
        }
        map.put("code", 200);
        map.put("data", result);
        return map;
    }

    @DeleteMapping("/{id}")
    public Map<String, Object> deleteCategory(@PathVariable("id") Integer id) {
        HashMap<String, Object> map = new HashMap<>();
        if(categoryService.deleteCategory(id)){
            map.put("code", 200);
            map.put("data", true);
        } else {
            map.put("code", 200);
            map.put("data", false);
        }
        return map;
    }

    @GetMapping("/all")
    public Map<String, Object> getAllCategory2() {
        HashMap<String, Object> map = new HashMap<>();
        List<Category> result = categoryService.list().stream().peek(c -> c.setLevelName(c.getParentId() == null ? "一级" : "二级")).collect(Collectors.toList());
        map.put("code", 200);
        map.put("data", result);
        return map;
    }
}
